//
//  LoadViewController.swift
//  fsapp
//
//  Created by zguang on 17/8/15.
//  Copyright © 2017年 huangshengjie. All rights reserved.
//

import UIKit
import  Alamofire
import SDWebImage
import SVProgressHUD
class LoadViewController: UIViewController {

    let ussd = UserSave()
    var sessionID = ""
    var time:Timer!
    var imageLoad = UIImageView()
    var skip = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let userDefault = UserDefaults.standard
        userDefault.set(String(describing: idfa), forKey: "idfa")
        getImage()
        skip.frame = CGRect(x:SCREEN_WIDTH - width(200),y:height(70),width:width(150),height:height(50))
        skip.layer.cornerRadius = 6
        skip.titleLabel?.font = UIFont.systemFont(ofSize: height(28))
        skip.backgroundColor = UIColor.init(red: 0, green: 0/255, blue: 0/255, alpha: 0.5)
        skip.setTitle(" 点击跳过", for: .normal)

       // self.present(CusTomTabBar(), animated: true, completion: nil)
        self.view.addSubview(self.imageLoad)
         //  self.view.backgroundColor = UIColor.red
        imageLoad.frame = self.view.frame
       
              // Do any additional setup after loading the view.
        
        
    }
    
    
    override func viewDidAppear(_ animated: Bool) {
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        tick()
    }
    
    static func jsonjson(aa:Any) -> JSON{
       let ab = JSON(aa)
       return  ab
    }
    
    
func CusTomTabBar() ->UITabBarController{
        let vc1 = IndexViewController()
        let vc2 = FillLearningViewController.init(typee: "0")
        let vc3 = FillLearningViewController.init(typee: "1")//FAQViewController()
        let vc4 = FillLearningViewController.init(typee: "2")
        let vc5 = MineViewController()
        
        
        let vcRegist = RegistViewController()
        let nvc1:UINavigationController = UINavigationController(rootViewController: vc1)
        let nvc2:UINavigationController = UINavigationController(rootViewController: vc2)
        let nvc3:UINavigationController = UINavigationController(rootViewController: vc3)
        let nvc4:UINavigationController = UINavigationController(rootViewController: vc4)
        let nvc5:UINavigationController = UINavigationController(rootViewController:vc5)
    let size  = CGSize.init(width: getWidth(width: 50), height: getHeight(50))
    let image = UIImage()

    let tabbar1 = UITabBarItem(title: "首页", image: UIImage(named:"bottom_icon1"), selectedImage:  UIImage(named:"bottom_icon1"))
       // tabbar1.imageInsets = UIEdgeInsetsMake(getHeight(25), width(25), getHeight(25), width(25))
        let tabbar2 = UITabBarItem(title: "完整学习", image: UIImage(named:"bottom_icon2"), selectedImage:  UIImage(named:"bottom_icon2"))
    let tabbar3 = UITabBarItem(title: "学习解惑",image: UIImage(named:"bottom_icon3"), selectedImage:  UIImage(named:"bottom_icon3"))
        let tabbar4 = UITabBarItem(title: "生活应用", image: UIImage(named:"bottom_icon4"), selectedImage:  UIImage(named:"bottom_icon4"))
    let tabbar5 = UITabBarItem(title: "我的",image: UIImage(named:"bottom_icon5"), selectedImage:  UIImage(named:"bottom_icon5"))
        nvc1.tabBarItem = tabbar1;
        nvc2.tabBarItem = tabbar2;
        nvc3.tabBarItem = tabbar3;
        nvc4.tabBarItem = tabbar4;
        nvc5.tabBarItem = tabbar5;
        let tc = UITabBarController()
        tc.tabBar.tintColor = naviColor
        nvc1.navigationController?.title = "首页"
        nvc2.title = "完整学习"
        nvc3.title = "学习解惑"
        nvc4.title = "生活应用"
        nvc5.title = "我的"
        tc.viewControllers = [nvc1,nvc2,nvc3,nvc4,nvc5]
        // tc.tabBar.backgroundImage = Public.getImgView("3.png")tc.viewControllers = [nvc1,nvc2,nvc3,nvc4,nvc5];return tc;
        return tc
    }

    func scale(toSize img: UIImage, size: CGSize) -> UIImage {
        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
        UIGraphicsBeginImageContext(size)
        // 绘制改变大小的图片
        img.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        // 从当前context中创建一个改变大小后的图片
        let scaledImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        // 使当前的context出堆栈
        UIGraphicsEndImageContext()
        // 返回新的改变大小后的图片
        return scaledImage!
    }
    
    
    func tick(){
        
        
         //self.Alarequest()
        let userDefault = UserDefaults.standard
         if let Session = userDefault.object(forKey: "password") as? String
         {
            if Session == ""{
              self.Alarequest()
            }
            self.present(CusTomTabBar(), animated: false, completion: nil)
         }else{
             //self.Alarequest()
             self.present(CusTomTabBar(), animated: false, completion: nil)
        }
        
        
        
//        let usd = UserSave()
//        print(usd.readInfo())
//        let loginNav = UINavigationController(rootViewController:LoginViewController());
//        if usd.readInfo().count<2{
//            self.present(loginNav, animated: false, completion: nil)
//        }
//        else{
//            if usd.readInfo()[2] == ""{
//                self.present(loginNav, animated: false, completion: nil)
//            }else{
//                self.present(CusTomTabBar(), animated: false, completion: nil)
//            }
//        }
//        

    
    }
    
    func Alarequest(){
        //let account:String = self.loginview.phoneText.text!;
        //let password:String = self.loginview.passwordText.text!
        let url = "http://dahan-api.heiyou.net/index.php/home/user/visitorLogin"
        let paramdic =
            ["udid":String(describing: idfa)]
        
        Alamofire.request( url, method: .post, parameters: paramdic).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
                
            }else{
                print("网络异常")
            }
            // print(response.response?.allHeaderFields)
            
            
            if let cookies =  HTTPCookieStorage.shared.cookies{
                print(cookies)
                self.saveCookies(response: response)
                //          let usr = UserDefaults.standard
                //  usr.set(cookies as [String:String], forKey: "savedCookies")
                //  UserDefaults.standard.synchronize()
                //print(cookies)
                for cookie in cookies{
                    self.sessionID = String(cookie.name)+("=") + String(cookie.value)
                }
                
                
                //存储用户Cookie

                let userDefault = UserDefaults.standard
                userDefault.set(self.sessionID, forKey: "Cookie")
                
            }else {
                print("登录出错,未获取到sessionID")
                return
            }
            
            if self.sessionID == "" {
                print("登录出错,未获取到sessionID")
                //return
            }
            
            
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
                DispatchQueue.main.async {
                    if(js["status"]==200){
                        
                     //SVProgressHUD.showSuccess(withStatus: "游客登录成功")
                        
                 //       print(self.jsonjson(aa: response.result.value))
                        //let usd = UserDefaults()
                        self.ussd.deleteInfo()
                        //self.ussd.saveInfo("1","18850076841", "1","0", "1","1","1","1","1", "1",sessionID: self.sessionID)

              if let name = js["result"]["name"].string{
                if let img = js["result"]["img"].string{
                    if let sex = js["result"]["sex"].string{
                        print(name)
                        self.ussd.saveInfo("1", "18850076841", "", "", name,sex, img, "", "", "", sessionID: self.sessionID)
                    }else{
                        self.ussd.saveInfo("1", "18850076841", "", "", name, "", img, "", "", "", sessionID: self.sessionID)
                    }
                   }
                
              }else{
                     print("获取个人信息失败")
                }
//                           // usd.set("", forKey: "name")
//                         }
//                        if let account = js["result"]["img"].string{
//                           usd.set("", forKey: "account")
//                        }else{
//                           usd.set("", forKey: "account")
//                        }
//                        if let img = js["result"]["img"].string{
//                            usd.set(img, forKey: "img")
//                        }else{
//                            usd.set("", forKey: "img")
//                        }
                        print(self.ussd.readInfo())
                    
                        
                        
                }
                
            }}
        
        // print(account+password)
    }
    }
    
    
    func saveCookies(response: DataResponse<Any>) {
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.response?.url
        //let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        if let cookies =  HTTPCookieStorage.shared.cookies{
            var cookieArray = [[HTTPCookiePropertyKey: Any]]()
            for cookie in cookies {
                cookieArray.append(cookie.properties!)
            }
            UserDefaults.standard.set(cookieArray, forKey: "savedCookies")
           // UserDefaults.standard.set(cookieArray, forKey: "Cookies")
            UserDefaults.standard.synchronize()
            print(cookies)
        }
    }


    
    
    func getImage (){
      let url = "http://dahan-api.heiyou.net/index.php/home/index/getActionImg"
        
        Alamofire.request( url, method: .post).responseJSON{ response in
            print("result=========================")
            if let sds = response.response{
            }else{
                SVProgressHUD.showError(withStatus: "网络连接失败，请检查后重试")
                print("网络异常")
            }
            if let JSON2 = response.result.value {
                let js = JSON(JSON2)
                print(js)
              
                DispatchQueue.main.async {
                    
                    
                    self.time =  Timer.scheduledTimer(timeInterval: 13, target: self, selector: #selector(self.tick), userInfo: nil, repeats: false)

                    if let iurl = js["result"]["img_url"].string{
                        let url =  URL(string:iurl)
                        //self.imageLoad.imageFromURL(iurl, placeholder: UIImage(named:"blank")!)
                        //var imageURL:NSURL = NSURL(string: "http://www.szplanner.com/images/inside/product_thumb.jpg")!
                        self.imageLoad.sd_setImage(with: url, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
                            // Perform operation.
                          //  self.imageLoad.addSubview(self.skip)
                        })
                        
                        self.skip.addTarget(self, action: #selector(self.tick), for: .touchUpInside);
                        

                    }
                
                }
            }
        }

    }
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
